const http = require("http");
const fs = require("fs");
const url = require("url");
const qs = require("querystring");

http.createServer((req, res)=>{
    if(req.url.includes("/api")){
        dataMiddleware(req,res)
    }else{
        staticHandle(req,res);
    }
}).listen(3000);

function staticHandle(req,res){
    const path = url.parse(req.url).pathname;
    fs.readFile("./www" + path, (err, data)=>{
        if(err){
            res.write("404");
        }else{
            res.write(data);
        }
        res.end();
    })
}
function dataMiddleware(req,res){
    if(req.method === "GET"){
        const getData = url.parse(req.url, true).query;
        dataHandle(req,res,getData);
    }else if(req.method === "POST"){
        let str = "";
        req.on("data", (d)=>{
            str += d;
        })
        req.on("end", ()=>{
            const postData = qs.parse(str);
            dataHandle(req,res,postData);
        })
    }else{
        errorHandle(res, 0);
        res.end();
    }
}

function dataHandle(req, res, reqData){
    switch(reqData.type){
        case "getGoods":
            getGoods(req, res, reqData);
            break;
        case "login":
            login(req, res, reqData);
            break;
        case "register":
            register(req, res, reqData);
            break;
        default:
            errorHandle(res, 1);
    }
}

// 获取商品数据接口
function getGoods(req, res, reqData){
    fs.readFile("./data/goods.json", "utf-8", (err,data)=>{
        res.write(data);
        res.end();
    })
}

const userMsg = [];
function login(req,res,reqData){
    let i=0;
    const flag = userMsg.some((val,idx)=>{
        i = idx;
        return val.username === reqData.username
    })
    if(flag){
        if(reqData.password === userMsg[i].password){
            res.write("登录成功");
            res.end();
        }else{
            res.write("登录失败，密码不对");
            res.end();
        }
    }else{
        res.write("用户名未注册");
        res.end();
    }
}
function register(req,res,reqData){
    let i=0;
    const flag = userMsg.some((val,idx)=>{
        i = idx;
        return val.username === reqData.username
    })
    if(flag){
        res.write("用户名已存在");
        res.end();
    }else{
        userMsg.push({
            username:reqData.username,
            password:reqData.password
        })
        res.write("注册成功");
        res.end();
    }
}

function errorHandle(res, type){
    if(type === 0){
        res.write("接收到未知请求方式，无法处理，请检查")
    }else if(type === 1){
        res.write("接收到未知功能，无法处理，请检查")
    }
    res.end();
}

